package com.itheima.service.Impl;

import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.utils.MapperUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

//业务层接口实现类
public class UserServiceImpl implements UserService {
    @Override
    //查找所有用户
    public List<User> findAll() {
        List<User> list = null;
        //获取sqlSession对象
        SqlSession sqlSession = MapperUtils.getSqlSession();
        //获取映射对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        list = mapper.findAll();
        //释放资源
        sqlSession.close();
        return list;
    }

    @Override
    //通过ids进行删除
    public void deleteByIds(String ids) {
        //System.out.println(ids);
        //分割ids变成数组
        String[] idStr = ids.split(",");
        //转数字
        Integer[] idArr = new Integer[idStr.length];
        for (int i = 0; i < idStr.length; i++) {
            idArr[i] = Integer.parseInt(idStr[i]);
        }

        //获取sqlSession对象
        SqlSession sqlSession = MapperUtils.getSqlSession();
        //获取映射对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteByIds(idArr);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

    @Override
    //通过user对象添加用户 返回改变行数
    public Integer saveUser(User user) {

        //获取sqlSession对象
        SqlSession sqlSession = MapperUtils.getSqlSession();
        //获取映射对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Integer changeLine = mapper.saveUser(user);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();

        return null;
    }

    @Override
    public User findById(String uid) {
        User user = null;

        //获取sqlSession对象
        SqlSession sqlSession = MapperUtils.getSqlSession();
        //获取映射对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        user = mapper.findById(uid);
        //提交事务
//        sqlSession.commit();
        //释放资源
        sqlSession.close();

        return user;
    }

    @Override
    public void update(User user) {
        //获取sqlSession对象
        SqlSession sqlSession = MapperUtils.getSqlSession();
        //获取映射对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.update(user);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }
}
